var express = require('express');
var router = express.Router();
var request = require('request');

var CommonJS = require('../../common/common');
var DBConfig = require('../../db/dbconfig');
var Wx_config = require('../../wx_config/wx_config');
var mysql = require('mysql');
var pool = mysql.createPool(DBConfig.mysql2);
// 分页 每页2个
var count = 20;

/*
 * 订单状态
 * 客户：     order_status   shipping_status  status
 * 1.待付款    1              1                1
 * 2.已付款    2              -      
 * 3.已取消    3              -
 * 4.已完成    4              3
 * 5.待评价    5              3
 * 6.已评价    6              3
 * 7.已退款    7
 * 全部        -              -                1
 * 待付款      1              1
 * 配送中      2              2
 * 已完成      4              3
 * 待评价      5              3
 * 仓库：shipping_status
 * 1.待分配    2              1
 * 2.已分配    2              2
 * 3.已送达    2              3
 * 4.订单异常  2              4
 * 订单系统状态 status
 * 1. 有效
 * 2. 删除
 *   
 */
// 订单列表
router.get('/jkyx/pc/order_list', function(req, res, next) {
	var param = req.query || req.params; 
	var page = param.page || 1;
	
	var srart = (page - 1) * count;
	// 获取今天的时间戳
	var today = CommonJS.getNowFormatDateDay();
	today = today + ' 00:00:00';
	var time = CommonJS.formatToTimestamp(today);
	
	var start_time = param.start_time || '';
	if (start_time == '') {
		start_time = time;
	} else{
		start_time = CommonJS.formatToTimestamp(start_time);	
	}
	
	
    pool.getConnection(function(err, connection) {
		if(err){
			res.end(JSON.stringify({
     			msg: '数据库连接失败',
     			status:'101',
     		}));
		}
		// 获取所有有效订单号
		connection.query(DBConfig.pc_order_list,[start_time,start_time,srart,count],function (err, results) {
			if (err){
			  	res.end(JSON.stringify({
	     			msg: '数据库查询失败',
	     			status:'102',
	     			err: err
	     		}));
			}else{
				var allOrders = results;
				getOrderGoods(allOrders,connection,res,page);
			}
		})
	})
});
// 订单搜索
router.get('/jkyx/pc/order_search', function(req, res, next) {
	var param = req.query || req.params; 
	var page = param.page || 1;
	
	var srart = (page - 1) * count;
	var select_value = param.select_value || 0;
	var keyword = param.keyword || '';
	
	// 获取今天的时间戳
	var today = CommonJS.getNowFormatDateDay();
	today = today + ' 00:00:00';
	var time = CommonJS.formatToTimestamp(today);
	
	var start_time = param.start_time || '';
	if (start_time == '') {
		start_time = time;
	} else{
		start_time = CommonJS.formatToTimestamp(start_time);	
	}
	
	
	if (select_value == 0) {
		res.end(JSON.stringify({
 			msg: '请选选择类别',
 			status:'106',
 		}));
 		return;
	} 
	var search_sql = '';
	switch (select_value){
		case '1': // 收货人姓名
			search_sql = 'select * from orders where status = 1 AND consignee like "%' + keyword + '%" and add_time > ? order by create_time desc;';
			break;
		case '2': // 收货人电话
			search_sql = 'select * from orders where status = 1 AND consignee_tel like "%' + keyword + '%" and add_time > ? order by create_time desc;';
			break;
		case '3': // 收货人订单号
			search_sql = 'select * from orders where status = 1 AND order_no like "%' + keyword + '%" and add_time > ? order by create_time desc;';
			break;
		default:
			break;
	}
	
    pool.getConnection(function(err, connection) {
		if(err){
			res.end(JSON.stringify({
     			msg: '数据库连接失败',
     			status:'101',
     		}));
		}
		// 获取所有有效订单号
		connection.query(search_sql,[start_time],function (err, results) {
			if (err){
			  	res.end(JSON.stringify({
	     			msg: '数据库查询失败',
	     			status:'102',
	     			err: err
	     		}));
			}else{
				var allOrders = [];
				allOrders.push([
					{
						'count(*)': results.length
					}
				]);
				allOrders.push(results)
				getOrderGoods(allOrders,connection,res,page);
			}
		})
	})
});


// 订单详情
router.get('/jkyx/pc/order_detail', function(req, res, next) {
	var param = req.query || req.params; 
	// 订单ID
	var order_id = param.order_id || '';
	if (order_id == '') {
		res.end(JSON.stringify({
 			msg: '请传入订单ID',
 			status:'101',
 		}));
 		return;
	}
    pool.getConnection(function(err, connection) {
		if(err){
			res.end(JSON.stringify({
     			msg: '数据库连接失败',
     			status:'101',
     		}));
		}
		// 获取订单详情
		connection.query(DBConfig.pc_order_detail,[order_id],function (err, results) {
			if (err){
			  	res.end(JSON.stringify({
	     			msg: '数据库查询失败',
	     			status:'102',
	     			err: err
	     		}));
			}else{
				var allOrders = [];
				allOrders.push([
					{
						'count(*)': 0
					}
				]);
				allOrders.push(results);
				getOrderGoods(allOrders,connection,res,1);
			}
		})
	})
});
// 修改订单备注
router.get('/jkyx/pc/order_mark', function(req, res, next) {
	var param = req.query || req.params; 
	var remark = param.remark || '';
	var descr = param.descr || '';
	var order_id = param.order_id || '';
	
    pool.getConnection(function(err, connection) {
		if(err){
			res.end(JSON.stringify({
     			msg: '数据库连接失败',
     			status:'101',
     		}));
		}
		// 获取所有有效订单号
		connection.query(DBConfig.pc_modify_order_mark,[remark,descr,order_id],function (err, results) {
			if (err){
			  	res.end(JSON.stringify({
	     			msg: '数据库查询失败',
	     			status:'102',
	     			err: err
	     		}));
			}else{
				res.end(JSON.stringify({
	     			msg: '操作成功',
	     			status:'100'
	     		}));
			}
		})
	})
});
// 修改订单价格
router.get('/jkyx/pc/order_amount', function(req, res, next) {
	var param = req.query || req.params; 
	var amount = param.amount || '';
	var id = param.id || ''; // 订单ID
	
    pool.getConnection(function(err, connection) {
		if(err){
			res.end(JSON.stringify({
     			msg: '数据库连接失败',
     			status:'101',
     		}));
		}
		// 获取所有有效订单号
		connection.query(DBConfig.pc_modify_order_amount,[amount,id],function (err, results) {
			if (err){
			  	res.end(JSON.stringify({
	     			msg: '数据库查询失败',
	     			status:'102',
	     			err: err
	     		}));
			}else{
				res.end(JSON.stringify({
	     			msg: '操作成功',
	     			status:'100'
	     		}));
			}
		})
	})
});

// 处理订单列表中的商品
function getOrderGoods(allOrders2,connection,res,page){
	var order_nos = '';
	var account_ids = '';
	var allOrders = allOrders2[1];
	var allOrders_Len = allOrders.length;
	if (allOrders_Len == 0) {
		res.end(JSON.stringify({
 			msg: '操作成功',
 			status:'100',
 			orders: []
 		}));
 		return;
	}
	for (var j = 0; j < allOrders_Len; j ++) {
		order_nos = order_nos + allOrders[j].order_no + ',';
		account_ids = account_ids + allOrders[j].account_id + ',';
	} 
	// 去掉最后一个','
	order_nos = order_nos.substring(0,(order_nos.length - 1));
	account_ids = account_ids.substring(0,(account_ids.length - 1));
	var provinces = 'select region_name,region_id from region where region_id in (select province_id from orders where order_no in (' + order_nos +'));';
	var citys = 'select region_name,region_id from region where region_id in (select city_id from orders where order_no in (' + order_nos +'));';
	var areass = 'select region_name,region_id from region where region_id in (select areas_id from orders where order_no in (' + order_nos +'));';
	var areas = 'select region_name,region_id from region where region_id in (select area_id from orders where order_no in (' + order_nos +'));';
	var shoopers = 'select * from mail_admin where id in (select shooper_id from orders where order_no in (' + order_nos +'));';
	var users = 'select * from account where id in (' + account_ids + ');';
	var sql1 = 'select * from order_goods where order_id in (' + order_nos + ');';
	var selSql = sql1 + provinces + citys + areass + areas + shoopers + users;
	// 获取订单中的商品 商品ID  规格ID  商品数量
	connection.query(selSql,function (err, results) {
		if (err){
		  	res.end(JSON.stringify({
     			msg: '数据库查询失败',
     			status:'102',
     			err: err
     		}));
		}else{
		    r_provinces = results[1]; // 省
		    r_provinces_len = r_provinces.length;
		    r_citys = results[2];  // 市
		    r_citys_len = r_citys.length;
		    r_areass = results[3]; // 区
		    r_areass_len = r_areass.length;
		    r_areas = results[4];  // 街道
		    r_areas_len = r_areas.length;
		    r_shoopers = results[5];  // 配送人
		    r_shoopers_len = r_shoopers.length;
		    r_users = results[6];  // 会员
		    r_users_len = r_users.length;
		    // 处理商品
			var retGoods = results[0];
			// 处理商品
			var goodsIDS = ''; // 商品IDs
			var specIDS = ''; // 规格
			var retGoods_Len = retGoods.length;
			for (var j = 0; j < retGoods_Len; j ++) {
				goodsIDS = goodsIDS + retGoods[j].goods_id + ',';
				specIDS = specIDS + retGoods[j].spec_id + ',';
			} 
			// 去掉最后一个','
			goodsIDS = goodsIDS.substring(0,(goodsIDS.length - 1));
			specIDS = specIDS.substring(0,(specIDS.length - 1));
			var selGoods = 'select * from goods where id in (' + goodsIDS + '); select * from goods_spec where id in (' + specIDS + ');';
			connection.query(selGoods,function (err, results) {
				connection.release();
				if (err){
				  	res.end(JSON.stringify({
		     			msg: '数据库查询失败',
		     			status:'103',
		     			err: err
		     		}));
				}else{
					// 处理商品
					var cartGoods = results[0];
					var cartGoods_len = cartGoods.length;
					// 加规格
					var cartSpecs = results[1];
					var cartSpecs_len = cartSpecs.length;
					var retOreders = [];
					// 订单循环遍历
					for (var j = 0; j < allOrders_Len; j ++) {
						var order_item = {};
						var tempGoods = [];
						var order_num = 0;
						// 商品循环遍历 
						for (var i = 0; i < retGoods_Len; i ++) {
							if (allOrders[j].order_no == retGoods[i].order_id) {
								var good = getGoods(cartGoods,retGoods[i].goods_id);
								var spec = getSpecs(cartSpecs,retGoods[i].spec_id);
								var num = retGoods[i].num;
								order_num = order_num + num;
								var item = {
									id: good.id, // 商品ID
									name: good.name, // 商品名字
									descr: good.descr, // 商品描述
									imgs: good.imgs, // 商品轮播图
									detail_imgs: good.detail_imgs, // 商品详细
									spec: {
										id: spec.id,  // 规格ID
										price: spec.price, // 价格
										origprice: spec.origprice, // 原价
										spec: spec.spec, // 规格
										salecount: spec.salecount,  // 销量
										stock: spec.stock, // 库存
									},
									num: num,  // 商品数量
								}
								tempGoods.push(item);
							}
						}
						// 订单地址
						var order_address = {
							provice_name: '', // 省份
							city_name: '',  // 市
							areas_name: '', // 区
							area_name: '',  // 街道
							address: allOrders[j].address // 详细地址	
						}
						// 省份
						for (var a = 0; a < r_provinces_len; a++) {
							if(allOrders[j].province_id == r_provinces[a].region_id){
								order_address.provice_name = r_provinces[a].region_name; 
							}
						}
						// 市
						for (var a = 0; a < r_citys_len; a++) {
							if(allOrders[j].city_id == r_citys[a].region_id){
								order_address.city_name = r_citys[a].region_name;
							}
						}
						// 区
						for (var a = 0; a < r_areass_len; a++) {
							if(allOrders[j].areas_id == r_areass[a].region_id){
								order_address.areas_name = r_areass[a].region_name; 
							}
						}
						// 街道
						for (var a = 0; a < r_areas_len; a++) {
							if(allOrders[j].area_id == r_areas[a].region_id){
								order_address.area_name = r_areas[a].region_name;
							}
						}
						// 收货人
						var order_consignee = {
							consignee: '', // 收货人姓名
							consignee_tel: '' // 收货人手机号
						}
						for (var a = 0; a < r_shoopers_len; a++) {
							if(allOrders[j].shooper_id == r_shoopers[a].id){
								order_consignee = {
									consignee: r_shoopers[a].name, // 收货人姓名
									consignee_tel: r_shoopers[a].telno // 收货人手机号
								}
							}
						}
						// 会员
						var order_user = {
							account_id: '', // ID
							account: '', // 手机号
							nickname: '' // 昵称
						}
						for (var a = 0; a < r_users_len; a++) {
							if(allOrders[j].account_id == r_users[a].id){
								order_user = {
									account_id: r_users[a].id, // ID
									account: r_users[a].account, // 手机号
									nickname: r_users[a].nickname // 昵称
								}
							}
						}
						
						order_item = {
							id: allOrders[j].id,
							order_no: allOrders[j].order_no,
							consignee: allOrders[j].consignee,
							consignee_tel: allOrders[j].consignee_tel,
							payment_id: allOrders[j].payment_id,
							freight_amount: allOrders[j].freight_amount,
							amount: allOrders[j].amount,
							pay_amount: allOrders[j].pay_amount,
							recharge_pay_amount: allOrders[j].recharge_pay_amount,
							pay_amount_other: allOrders[j].pay_amount_other,
							is_print_price: allOrders[j].is_print_price,
							defray_type: allOrders[j].defray_type,
							order_type: allOrders[j].order_type,
							order_status: allOrders[j].order_status,
							shipping_status: allOrders[j].shipping_status,
							shipping_timer: allOrders[j].shipping_timer,
							coupon_id: allOrders[j].coupon_id,
							remark: allOrders[j].remark,
							descr: allOrders[j].descr,
							transaction_id: allOrders[j].transaction_id,
							create_time: allOrders[j].create_time,
							pay_time: allOrders[j].pay_timer,
							num: order_num,
							goods: tempGoods,
							order_address: order_address,
							order_consignee: order_consignee,
							order_user: order_user
						}
						retOreders.push(order_item);
					} 

					// 分页 每页 2 个 
					var len = allOrders2[0][0]['count(*)'];
					var allPage = parseInt(len)/count;  // 总页数
					var pageStr = allPage.toString();
					// 不能被整除
					if (pageStr.indexOf('.')>0) {
						allPage = parseInt(pageStr.split('.')[0]) + 1; 
					}
					res.end(JSON.stringify({
		     			msg: '操作成功',
		     			status:'100',
		     			allPage: allPage,
		     			page: page,
		     			orders: retOreders,
		     			total_count: len
		     		}));	  
				}
			})
		}
	})
}

// 根据商品 ID  寻找商品数组中的商品
// goods: 商品数组
// goods_id: 商品ID
function getGoods(goods,goods_id){
	var len = goods.length;
	for (var i = 0; i < len; i ++) {
		if (goods[i].id == goods_id) {
			if (typeof goods[i].imgs === 'string') {
				goods[i].imgs = JSON.parse(goods[i].imgs);
			}
			return goods[i];
		}
	}
	return false;
}
// 根据规格ID 寻找规格数组中的规格
// specs: 规格数组
// spec_id: 规格ID
function getSpecs(specs,spec_id){
	var len = specs.length;
	for (var i = 0; i < len; i ++) {
		if (specs[i].id == spec_id) {
			return specs[i];
		}
	}
	return false;
}

module.exports = router;
